import { useEffect, useRef, useState } from "react";
import PropTypes from "prop-types";
import Typed from "typed.js";
import { history } from "umi";
import "./DialogStyles.css";

const Dialog = ({
	backgroundImage,
	dialogues,
	nextPage,
	triggerIndexEvents,
	eventHandlers,
	dialogueImages,
}) => {
	const [currentIndex, setCurrentIndex] = useState(0);
	const typedRef = useRef(null);
	const typedJS = useRef(null);

	useEffect(() => {
		// Destroy the previous Typed.js instance
		if (typedJS.current) {
			typedJS.current.destroy();
		}

		if (dialogues[currentIndex]) {
			typedJS.current = new Typed(typedRef.current, {
				strings: [dialogues[currentIndex]],
				typeSpeed: 100,
				showCursor: false,
			});
		}
		if (triggerIndexEvents && eventHandlers) {
			const eventIndex = triggerIndexEvents.indexOf(currentIndex);
			if (
				eventIndex !== -1 &&
				typeof eventHandlers[eventIndex] === "function"
			) {
				eventHandlers[eventIndex]();
			}
		}
	}, [currentIndex]);

	const handleClick = () => {
		if (typedJS.current && !typedJS.current.typingComplete) {
			// 删除前一个 Typed.js 实例
			typedJS.current.destroy();

			// 用完整的字符串重新实例化一个 Typed.js
			typedJS.current = new Typed(typedRef.current, {
				strings: [dialogues[currentIndex]],
				typeSpeed: 0,
				showCursor: false,
			});

			// 立即开始打字，由于`typeSpeed`已经设置为`0`，将会立即显示出完整的对话
			typedJS.current.start();

			// 返回，以免执行后面的代码
			return;
		}

		const nextIndex = currentIndex + 1;
		if (nextIndex < dialogues.length) {
			setCurrentIndex(nextIndex);
		} else if (nextPage) {
			history.push(nextPage);
		}
	};

	return (
		<div className="dialogBackground" onClick={handleClick}>
			{dialogueImages[currentIndex] &&
				dialogueImages[currentIndex].leftImage && (
					<img
						src={dialogueImages[currentIndex].leftImage}
						alt="Left character"
						className="dialogImageLeft"
					/>
				)}
			{dialogueImages[currentIndex] &&
				dialogueImages[currentIndex].rightImage && (
					<img
						src={dialogueImages[currentIndex].rightImage}
						alt="Right character"
						className="dialogImageRight"
					/>
				)}
			<div
				className="dialogBox"
				style={{
					backgroundImage: `url(${backgroundImage})`,
					padding: "6vw 12vw 6vw 12vw",
					margin: "20px",
				}}
			>
				<span ref={typedRef}></span>
			</div>
		</div>
	);
};

Dialog.propTypes = {
	backgroundImage: PropTypes.string.isRequired,
	dialogues: PropTypes.arrayOf(PropTypes.string).isRequired,
	disableClick: PropTypes.bool,
	nextPage: PropTypes.string,
	triggerIndexEvents: PropTypes.arrayOf(PropTypes.number),
	eventHandlers: PropTypes.arrayOf(PropTypes.func),
	dialogueImages: PropTypes.arrayOf(
		PropTypes.shape({
			leftImage: PropTypes.string,
			rightImage: PropTypes.string,
		})
	),
};

Dialog.defaultProps = {
	disableClick: false,
	triggerIndexEvents: [],
	eventHandlers: [],
	dialogueImages: [],
};

export default Dialog;
